<template>
  <div class="table-container">
    <div class="flex justify-between">
      <div class="flex gap-2">
        <a-input-search
          v-model="query.keyword"
          search-button
          :button-text="t['搜索']"
          :placeholder="t['价签编码']"
          @search="search"
          @keydown.enter="search"
          allow-clear
        />
      </div>
      <div class="flex items-center gap-2">
        <a-popover trigger="click">
          <a-button>{{ t["列配置"] }}</a-button>
          <template #content>
            <a-transfer
              v-model:model-value="tableConfig.defaultField"
              :data="transferColumns()"
              :title="[t['已隐藏'], t['已显示']]"
              @change="setColumns"
            />
          </template>
        </a-popover>
        <XDelete :disabled="selectedKeys.length <= 0" @ok="delByIds" />
      </div>
    </div>
    <a-divider></a-divider>
    <a-table
      v-model:selectedKeys="selectedKeys"
      page-position="bottom"
      :columns="columnsData"
      :loading="loading"
      :data="tableData"
      :row-selection="rowSelection"
      row-key="queueId"
      :pagination="{
        pageSize: query.pageSize,
        total: query.total,
        current: query.pageNum,
        showJumper: true,
        showPageSize: true,
        showTotal: true
      }"
      @page-size-change="pageSizeChange"
      @filter-change="filterChange"
      @page-change="pageChange"
    >
      <template #status="{ record }">
        <a-tag :color="getQueueStatus(record.status)?.color">
          {{ t[getQueueStatus(record.status)?.text] }}
        </a-tag>
      </template>
      <template #triggerType="{ record }">
        {{
          getOptionLabel({
            options: triggerOptions,
            value: record.triggerType
          })
        }}
      </template>
      <template #optional="{ record }">
        <a-button :disabled="record.status !== '4'" @click="retry(record)">
          {{ t["重新下发"] }}
        </a-button>
      </template>
      <template #err="{ record }">
        {{ t[errOptions[record.err]] }}
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { delSendqueue, listSendqueue, reissue } from "@/api/service/sendqueue/sendqueue";
import { QueueItem } from "@/api/service/sendqueue/types";
import { errOptions, getQueueStatus } from "@/data/options/status";

import { triggerOptions } from "@/data/options/options";
import useTableConfig from "@/hook/useTableConfig";

import { getQueueTableConfig } from "@/store/modules/form/form.utils";
import { getOptionLabel } from "@/utils/form";

import { Message } from "@arco-design/web-vue";
import { columns, transferColumns } from "./columns";

const { rowSelection, selectedKeys } = useTableConfig(columns);
const tableData = ref([] as Array<QueueItem>);
const t = translate("公共模块");
const tableConfig = getQueueTableConfig();
const loading = ref(true);
const props = defineProps<{
  /* 标签 */
  tagCode?: string;
  batchName?: string;
}>();
const queryObject = {
  batchName: "",
  keyword: "",
  pageNum: 1,
  pageSize: 20,
  total: 0
};

const query = useQuery({
  ...queryObject
});
function getList() {
  loading.value = true;
  tableData.value = [];
  listSendqueue(query.value).then((res) => {
    tableData.value = res.rows;
    query.value.total = res.total;
    loading.value = false;
  });
}
const getListByBatchName = async (batchName: string) => {
  query.value.batchName = batchName;
  getList();
};

const columnsData = computed(() => {
  return useCloned(columns).cloned.value.filter((item) => {
    item.title = t.value?.[item.title as string];
    item.align = "center";
    if (!item.width) item.width = 120;
    item.slotName = item.dataIndex;
    return Object.values(tableConfig.defaultField).findIndex((e) => e === item.dataIndex) > -1;
  });
});

watch(
  props,
  () => {
    if (props.tagCode) {
      query.value.tagCode = props.tagCode;
    }
    if (props.batchName) {
      query.value.batchName = props.batchName;
    }
    getList();
  },
  {
    deep: true,
    immediate: true
  }
);
function pageChange(index: number) {
  query.value.pageNum = index;
  getList();
}

async function delByIds() {
  await delSendqueue(selectedKeys.value);
  selectedKeys.value = [];
  getList();
  selectedKeys.value = [];
}

const retry = async (item: QueueItem) => {
  const { msg } = await await reissue(item.queueId);
  Message.info(msg);
  getList();
};

const setColumns = () => {
  if (tableConfig.defaultField.length === 0) {
    tableConfig.defaultField = [
      "tagCode",
      "goodsName",
      "status",
      "err",
      "sendTime",
      "index",
      "optional"
    ];
  }
};

const resetQuery = () => {
  query.value = {
    ...queryObject
  };
  getList();
};

const filterChange = (dataIndex: string, filteredValues: string[]) => {
  if (dataIndex === "resolutionDesc") {
    dataIndex = "resolutionId";
  }

  query.value[dataIndex] = filteredValues[0];
  getList();
};
const pageSizeChange = (size: number) => {
  query.value.pageSize = size;
  getList();
};

const search = () => {
  query.value.pageNum = 1;
  getList();
};

defineExpose({
  getListByBatchName,
  resetQuery
});
</script>
